from django_redis import get_redis_connection
from rest_framework import serializers


# 校验前端的短信验证码
class SMSCodeSerializer(serializers.Serializer):
    text = serializers.CharField(max_length=4, min_length=4, label='图片验证码')
    image_code_id = serializers.UUIDField(label='图片验证码编号')

    def validate(self, attrs):
        text = attrs['text']
        image_code_id = attrs['image_code_id']

        # 获取redis存储的text, image_code_id
        redis_conn = get_redis_connection('code')
        redis_text = redis_conn.get('image_code_%s' % image_code_id)

        # 判断验证码是否过期
        if not redis_text:
            raise serializers.ValidationError("验证码已过期")
        # 删除redis中的验证码
        redis_conn.delete('image_code_%s' % image_code_id)
        # 判断验证码是否正确
        if redis_text.decode().lower() != text.lower():
            raise serializers.ValidationError("验证码填写错误")

        return attrs

